package org.simp.codec;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.simp.core.message.SimpMessage;
import org.simp.core.message.SimpMessageWraper;
import org.simp.exception.SimpIncompleteException;

/**
 * @author zhuhaitao at 2014-5-22
 *
 * 发送消息编码器
 */
public class SimpResponseEncoder extends ProtocolEncoderAdapter {

	private static final Logger log = Logger.getLogger(SimpResponseEncoder.class);
	@Override
	public void encode(IoSession session, Object response, ProtocolEncoderOutput out)
			throws Exception {
		if(response instanceof SimpMessage){
			SimpMessage msg = (SimpMessage) response;
			try{
			byte[] data = msg.encode();
			log.debug(String.format(" SEND RESPONSE : FROM %1$s TO %2$s ,MSG CODE : %3$s %4$s",msg.getHead().getSrcAddress(),msg.getHead().getObjAddress(),msg.getHead().getMainId(),msg.getHead().getMoudleId()));
			out.write(IoBuffer.wrap(data));
			}catch (SimpIncompleteException e) {
				log.warn(e);
			}
		}else{
			log.error(" UNkonw msg ");
		}

	}

}
